package paper.dao.impl;

import java.util.Iterator;
import java.util.List;

import keter.dao.base.KeterAbstractDao;
import keter.domain.CodeList;
import keter.util.CollectionsUtil;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import paper.dao.MessageDao;
import paper.domain.Message;
import paper.domain.User;

import com.google.common.collect.Lists;

@Repository
public class MessageDaoImpl extends KeterAbstractDao<Message> implements MessageDao {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CodeList.class);

	/**
	 * <p>Method ：findInboxMessageByReceiverId
	 * <p>Description : 收件箱查找
	 * 
	 * @see paper.dao.PrivateMessageDao#findInboxByReceiverId(java.lang.Long)
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@Override
	public List<Message> findInboxByReceiverId(Long id) {
		String position = Message.Position.INBOX.toString();
		return getResultList("from Message pm "
				+ "where pm.receiver.id = :id and pm.position=:position order by created desc ", 
				wrap("id","position"),
				wrap(id,position)
			);
	}
	
	/**
	 * <p>Method ：findSentMessageBySenderId
	 * <p>Description : 发件箱查找
	 * 
	 * @see paper.dao.PrivateMessageDao#findSentMessageBySenderId(java.lang.Long)
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@Override
	public List<Message> findSentMessageBySenderId(Long id) {
		String position = Message.Position.SENT.toString();
		return getResultList("from Message pm where pm.sender.id = :id and pm.position=:position", 
				wrap("id","position"),
				wrap(id,position)
			);
	}

	@Override
	public void sendMessage(Message pm) {
		List<User> receiverList = Lists.newArrayList();
		receiverList.add(pm.getReceiver());
		sendMessage(pm,receiverList);
	}
	
	@Override
	public void sendMessage(Message pm, List<User> receiverList) {
		Message sentPm = (Message) pm.clone();//创建已发消息副本
		sentPm.setReceiverNames(CollectionsUtil.extractToString(receiverList, "name", ", "));
		sentPm.setPosition(Message.Position.SENT.toString());
		save(sentPm);//保存“已发消息”
		for (Iterator<User> iterator = receiverList.iterator(); iterator.hasNext();) {
		    User receiver = (User) iterator.next();
			pm.setReceiver(receiver);
			save(pm);//为每个接收者分别保存“接收消息”
		}
	}
	
	@Override
	public void deleteMessageById(Long id) {
		executeUpdate("delete from Message t where t.id=:id", 
                wrap("id"),
                wrap(id)
        );
	}
}
